package cn.gzsf.weibo.controller;


import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@RestController
public class UploadController {
    //@Value注解的作用是给下面的变量赋值
    //${xxx}会自动找到application.properties里面的配置信息
    @Value("${imagesPath}")
    private String dirPath;

    @RequestMapping("/upload")
    public String upload(MultipartFile picFile) throws Exception{
        //获取图片原始名
        String fileName = picFile.getOriginalFilename();
        //获取图片的后缀
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        //通过UUID拼接新的名称
        fileName = UUID.randomUUID()+suffix;
        //通过日期类拿到日期路径
        SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/");
        String datePath = sdf.format(new Date());
        //判断存储的文件夹是否存在
        //String dirPath = "d:/files";
        File dirFile = new File(dirPath + datePath);
        if(!dirFile.exists()){
            dirFile.mkdirs();
        }
        //把图片存入磁盘
        picFile.transferTo(new File(dirPath+datePath+fileName));
        //返回图片的路径
        System.out.println(datePath+fileName);
        return datePath+fileName;
    }


    @RequestMapping("/remove")
    public void remove(String url){
        new File(dirPath+url).delete();
    }
}
